﻿using AutoMapper;
using MediatR;
using SmartProduction.Domain.采购委外订单;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue.Interface;
using SmartProduction.Write.API.Application.Commands.DepartCommand;

namespace SmartProduction.Write.API.Application.CommandHandlers.DepartCommandHandler
{
    /// <summary>
    /// 部门添加命令处理
    /// </summary>
    public class DepartCreateCommandHandler : IRequestHandler<DepartCreateCommand, APIResult<object>>
    {
        /// <summary>
        /// AutoMapper
        /// </summary>

        private readonly IMapper mapper;

        /// <summary>
        /// 仓储-部门
        /// </summary>
        private readonly IBaseRepository<Depart> departRepository;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="departRepository">仓储-部门</param>
        public DepartCreateCommandHandler(IMapper mapper, IBaseRepository<Depart> departRepository)
        {
            this.mapper = mapper;
            this.departRepository = departRepository;
        }

        public async Task<APIResult<object>> Handle(DepartCreateCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            var info = mapper.Map<Depart>(request);
            var data = departRepository.AddAsync(info).Result;
            if (data > 0)
            {
                result.Code = APIEnums.添加成功;
                result.Msg = APIEnums.添加成功.ToString();
                result.data = data;
            }
            else
            {
                result.Code = APIEnums.添加失败;
                result.Msg = APIEnums.添加失败.ToString();
            }
            return await Task.FromResult(result);
        }
    }
}
